package com.yy.ttmodule.activity;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yy.ttmodule.Debug;
import com.yy.ttmodule.R;
import com.yy.ttmodule.cardStatus.BmChecker;
import com.yy.ttmodule.cardStatus.BmService;
import com.yy.ttmodule.cardStatus.StatusBean;
import com.yy.ttmodule.control.Constant;
import com.yy.ttmodule.control.ParamCons;
import com.yy.ttmodule.control.ParseParam;
import com.yy.ttmodule.manager.ControlManager;
import com.yy.ttmodule.udp.ConvertData;
import com.yy.ttmodule.udp.DataTypeConversion;
import com.yy.ttmodule.utils.GPSLocationManager;
import com.yy.ttmodule.utils.IPAddrUtils;
import com.yy.ttmodule.utils.Logger;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;

public class MainActivity extends BaseActivity implements View.OnClickListener, UdpClient.OnDataReceiveListener {

    private RelativeLayout Rel_test;

    private TextView txt_test;

    private EditText edit_dial_num;
    private TextView txt_dial_status;

    private EditText edit_sms_send;
    private TextView txt_sms_send;

    private TextView txt_net_status;
    private TextView txt_sign_val;
    private TextView txt_data_query;
    private TextView txt_data_set;

    private TextView txt_flight_query;
    private TextView txt_flight_set;
    private TextView txt_phone_num;
    private TextView txt_card_status;

    private TextView txt_call_rec;
    private TextView txt_hang_up;


    private TextView txt_phone_status;
    private TextView txt_reboot;
    private TextView txt_gps_query;

    private TextView txt_sms_rec;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GPSLocationManager.getInstances(this);

//        Constant.CLIENT_IP = IPAddrUtils.getIpAddress("eth0");
//        Constant.SERVER_IP = IPAddrUtils.getIpAddress("eth0");
//        Constant.CLIENT_IP = "127.0.0.1";
        Rel_test = (RelativeLayout) findViewById(R.id.Rel_test);

        if ( Debug.testDebug ) {
            Constant.SERVER_IP = "127.0.0.1";
            Rel_test.setVisibility(View.VISIBLE);
        }

        txt_test = (TextView) findViewById(R.id.txt_test);
        txt_test.setOnClickListener(this);

        edit_dial_num = (EditText) findViewById(R.id.edit_dial_num);
        txt_dial_status = (TextView) findViewById(R.id.txt_dial_status);
        txt_dial_status.setOnClickListener(this);

        edit_sms_send = (EditText) findViewById(R.id.edit_sms_send);
        txt_sms_send = (TextView) findViewById(R.id.txt_sms_send);
        txt_sms_send.setOnClickListener(this);

        txt_sms_rec = (TextView) findViewById(R.id.txt_sms_rec);

        txt_net_status = (TextView) findViewById(R.id.txt_net_status);
        txt_net_status.setOnClickListener(this);
        txt_sign_val = (TextView) findViewById(R.id.txt_sign_val);
        txt_sign_val.setOnClickListener(this);
        txt_data_query = (TextView) findViewById(R.id.txt_data_query);
        txt_data_query.setOnClickListener(this);
        txt_data_set = (TextView) findViewById(R.id.txt_data_set);
        txt_data_set.setOnClickListener(this);
        txt_flight_query = (TextView) findViewById(R.id.txt_flight_query);
        txt_flight_query.setOnClickListener(this);
        txt_flight_set = (TextView) findViewById(R.id.txt_flight_set);
        txt_flight_set.setOnClickListener(this);
        txt_phone_num = (TextView) findViewById(R.id.txt_phone_num);
        txt_phone_num.setOnClickListener(this);
        txt_card_status = (TextView) findViewById(R.id.txt_card_status);
        txt_card_status.setOnClickListener(this);

        txt_call_rec = (TextView) findViewById(R.id.txt_call_rec);
        txt_call_rec.setOnClickListener(this);
        txt_hang_up = (TextView) findViewById(R.id.txt_hang_up);
        txt_hang_up.setOnClickListener(this);


        txt_phone_status = (TextView) findViewById(R.id.txt_phone_status);
        txt_phone_status.setOnClickListener(this);
        txt_reboot = (TextView) findViewById(R.id.txt_reboot);
        txt_reboot.setOnClickListener(this);
        txt_gps_query = (TextView) findViewById(R.id.txt_gps_query);
        txt_gps_query.setOnClickListener(this);

        /*Thread td = new Thread(new UdpRxDataTask(null));
        td.start();*/
        addStatusBeanToMap(StatusBean.TYPE_CF_CARD);
        addStatusBeanToMap(StatusBean.TYPE_BM_BAR);

        startService();
        try {
            mBmCFChecker = new BmChecker(MainActivity.this, mMap.get(StatusBean.KEY_CF_CARD));
            mBmCFChecker.start();
            mBmCFChecker.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            mBmBarChecker = new BmChecker(MainActivity.this, mMap.get(StatusBean.KEY_BM_BAR));
            mBmBarChecker.start();
            mBmBarChecker.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private void addStatusBeanToMap(int type){
        StatusBean sb1 = new StatusBean(type);
        mMap.put(sb1.getName(), sb1);
    }

    Intent mIntent = new Intent();
    private void startService() {
        mIntent.setClass(mContext, BmService.class);
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startService(mIntent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.txt_test:
//                UdpClient.getInstance().sendByteCmd(
//                        new byte[]{(byte) 0xAA, 0x60, (byte) 0xAA, 0x60, 0x01, 0x00, 0x01, 0x0, 0x06, (byte) 0xE4,});
                break;
            case R.id.txt_net_status:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_NETWORK_ACCESS_STATUS),
                        new byte[]{ 0x00 });
                break;
            case R.id.txt_sign_val:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_SIGNAL_STRENGTH_QUERY),
                        new byte[]{ 0x00 });
                break;
            case R.id.txt_data_query:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_DATA_STATUS_QUERY),
                        new byte[]{ 0x00 });
                break;
            case R.id.txt_data_set:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_DATA_STATUS_SET),
                        new byte[]{ 0x09 });
                break;

            case R.id.txt_flight_query:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_FLIGHT_MODE_QUERY),
                        new byte[]{ 0x00 });
                break;
            case R.id.txt_flight_set:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_FLIGHT_MODE_SET),
                        new byte[]{ 0x02 });
                break;
            case R.id.txt_phone_num:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_LOCAL_PHONE_NUMBER_INQUIRY),
                        new byte[]{ 0x00 });
                break;
            case R.id.txt_card_status:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_CARD_STATUS_INQUIRY),
                        new byte[]{ 0x00 });
                break;

            case R.id.txt_call_rec:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_ANSWER),
                        new byte[]{ 0x00 });
                break;
            case R.id.txt_hang_up:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_HANG_UP),
                        new byte[]{ 0x00 });
                break;

            case R.id.txt_phone_status:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_CALL_STATUS_INQUIRY),
                        new byte[]{ 0x00 });
                break;
            case R.id.txt_reboot:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_REBOOT),
                        new byte[]{ 0x00 });
                break;
            case R.id.txt_gps_query:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_BEIDOU_NAV_QUERY),
                        new byte[]{ 0x00 });
                break;


            case R.id.txt_dial_status:
                UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_DIAL),
                        edit_dial_num.getText().toString().getBytes());
                break;
            case R.id.txt_sms_send:
                try {
                    if ( edit_dial_num.getText().toString().length() > 11
                            || edit_sms_send.getText().toString().length() > 70 ) {
                        return;
                    }
                    String number = edit_dial_num.getText().toString();
                    byte[] txtArr = edit_sms_send.getText().toString().getBytes("GBK");
                    byte[] res = new byte[number.getBytes().length + txtArr.length];

                    System.arraycopy(number.getBytes(), 0, res, 0, number.getBytes().length);
                    System.arraycopy(txtArr, 0, res, number.getBytes().length, txtArr.length);

                    UdpClient.getInstance().sendData(DataTypeConversion.shortToBytes(ParamCons.CMD_SEND_TEXT_MESSAGE),
                            res);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onDataReceive(byte[] buffer, int size) {
        try {
            int frameType = resolveDate(buffer,
                    ParseParam.FRAME_TYPE_ID, ParseParam.FRAME_TYPE_LEN);
            int len = resolveDate(buffer,
                    ParseParam.FRAME_LEN_ID, ParseParam.FRAME_LEN_LEN);
            int value = resolveDate(buffer,
                    ParseParam.FRAME_VALUE_ID, ParseParam.FRAME_VALUE_LEN);

            switch ( (frameType & 0xFF) ) {
                case ParamCons.CMD_NETWORK_ACCESS_STATUS_RES:
                    txt_net_status.setText("入网状态查询:" + (value == 1 ? "未入网":"入网待机"));
                    break;
                case ParamCons.CMD_SIGNAL_STRENGTH_QUERY_RES:
                    txt_sign_val.setText("信号强度: " + value);
                    break;
                case ParamCons.CMD_DATA_STATUS_QUERY_RES:
                    txt_data_query.setText("数据状态查询: " + value);
                    break;
                case ParamCons.CMD_DATA_STATUS_SET_RES:
                    txt_data_set.setText("数据状态设置结果: " + value);
                    break;

                case ParamCons.CMD_FLIGHT_MODE_QUERY_RES:
                    txt_flight_query.setText("飞行模式查询结果: " + value);
                    break;
                case ParamCons.CMD_FLIGHT_MODE_SET_RES:
                    txt_flight_set.setText("飞行模式设置结果: " + value);
                    break;
                case ParamCons.CMD_LOCAL_PHONE_NUMBER_RES:
                    byte[] dailNum = ConvertData.subBytes(buffer, ParseParam.FRAME_VALUE_ID, 11);
                    String strphone = new String(dailNum, StandardCharsets.US_ASCII);
                    txt_phone_num.setText("号码: " + strphone);
                    break;
                case ParamCons.CMD_CARD_STATUS_RES:
                    txt_card_status.setText("密卡状态: M卡" + value + ";M棒" + resolveDate(buffer,
                            ParseParam.FRAME_VALUE_ID + 1, ParseParam.FRAME_VALUE_LEN));
                    break;

                case ParamCons.CMD_INCOMING_CALL:
                    txt_call_rec.setVisibility(View.VISIBLE);
                    txt_hang_up.setVisibility(View.VISIBLE);
                    edit_dial_num.setText("" + new String(
                            ConvertData.subBytes(buffer, ParseParam.FRAME_VALUE_ID, 11),
                            StandardCharsets.US_ASCII));
                    break;

                case ParamCons.CMD_CALL_STATUS_INQUIRY:
                    txt_phone_status.setText("通话查询: " + value);
                    break;
                case ParamCons.CMD_SEND_TEXT_MESSAGE_RES:
                    txt_sms_send.setText("发短信: " + value);
                    break;
                case ParamCons.CMD_RECEIVE_SMS:
                    String strNumber = new String(
                            ConvertData.subBytes(buffer, ParseParam.FRAME_VALUE_ID, Constant.PHONE_NUM_LEN),
                            StandardCharsets.US_ASCII);
                    String smsText = new String(
                            ConvertData.subBytes(buffer, ParseParam.FRAME_VALUE_ID + Constant.PHONE_NUM_LEN,
                                    len - Constant.PHONE_NUM_LEN), "GBK");
                    edit_dial_num.setText("" + strNumber);
                    txt_sms_rec.setText("" + smsText);
                    break;
                case ParamCons.CMD_REBOOT_RES:
                    break;
                case ParamCons.CMD_BEIDOU_NAV_QUERY_RES:
                    if ( len == 1 ) {
                        txt_gps_query.setText("定位失败: " + value);
                    } else {
                        value = resolveDate(buffer,
                                ParseParam.FRAME_VALUE_ID + 8 + 1, ParseParam.FRAME_VALUE_LEN);
                        txt_gps_query.setText("定位纬度: " + (value == 0x4E ? "N" : "S"));
                    }
                    break;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if ( Debug.testDebug ) {
            UdpClient.getInstance().setOnDataReceiveListener(this);
            UdpClient.getInstance().connect(Constant.SERVER_IP, Constant.SERVER_PORT, Constant.CLIENT_PORT);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if ( Debug.testDebug ) {
            UdpClient.getInstance().disconnect();
        }
        closeThread(mBmCFChecker);
        mBmCFChecker = null;
        closeThread(mBmBarChecker);
        mBmBarChecker = null;
        if (mIntent != null && mContext != null) {
            mContext.stopService(mIntent);
        }
        GPSLocationManager.getInstances(this).stop();
    }

    private void closeThread(BmChecker thread) {
        if (null != thread) {
            thread.setStoped(true);
        }
    }

}
